import {onMounted,ref,shallowRef} from "vue"
import {useEventListener,useThrottle,useThrottleFn} from "@vueuse/core"

export const useBackTop=(props,emit,componentName)=>{
  const el=shallowRef();
  const container=shallowRef();
  const visible=ref(false);

  const handleScroll=()=>{
    if(el.value) visible.value=el.value.scrollTop>=props.visibilityHeight
  };

  const handleClick=(event)=>{
    el.value?.scrollTo({top:0,behavior:'smooth'})
    emit('click',event)
  }

  const handleScrollThrottled=useThrottleFn(handleScroll,300,true);
  useEventListener(container,'scroll',handleScrollThrottled);

  onMounted(()=>{
    container.value=document;
    el.value=document.documentElement;
    if(props.target){
      el.value=document.querySelector(props.target)??undefined
      container.value=el.value
    }
  })

  return{
    visible,
    handleClick
  }
}